<?php

// phpMyRealty 3
//
// File Name: login.php
// File Location : ./
//
// Copyright (c)2009 phpMyRealty.com
//
// e-mail: support@phpMyRealty.com

// Include configuration file and general functions
define('PMR', 'true');

include ( './config.php' );
include ( PATH . '/defaults.php' );

// ----------------------------------------------------------------------
// USER CONTROL PANEL SECTION

// Title tag content
$title = $conf['website_name_short'] . ' - ' . $lang['Menu_User_Login'];

// Authenticate user

// If no login or password session variable 
// set yet we create one, based  on the POST 
// variables passed from the auth form

if (!isset($_SESSION['login']) && isset($_POST['login']))
 {                
  $session->set('login', safehtml(strtolower($_POST['login'])));
  $session->set('password', md5($_POST['password']));
  $userlogin = FALSE;
 }

// Template header
include ( PATH . '/templates/' . $cookie_template . '/header.php' );

// If logged we can start the page output
if (auth_check($session->fetch('login'), $session->fetch('password')))
 {
  // Fetching the user ID from the user's table
  $sql = 'SELECT approved, id, package FROM ' . USERS_TABLE . ' WHERE approved = 1 AND login = "' . $session->fetch('login') . '" LIMIT 1';
  $r = $db->query( $sql );
  $f = $db->fetcharray( $r );

  // If this account is approved and approval is required, allow them to continue..
  if ((isset($f['approved']) && $f['approved'] == 1))
   {

    // If the user logo/photo was uploaded we start this routine
    if (isset($_POST['submit_logo']) 
    && $_POST['submit_logo'] == $lang['Realtor_Submit_Logo'])
     {

      // We think that the image is uploaded or will
      // return FALSE if the upload_image function
      // will fail
      $uploaded = TRUE;

      // Upload and resize the image
      upload_image ( 'photos', $f['id'], $_FILES['logo_file']['tmp_name'], $conf['photo_resampled_width'] ) or $uploaded = FALSE;

     }

    // If user removed the logo/photo we run the following
    if (isset($_POST['submit_logo_remove']) 
    && $_POST['submit_logo_remove'] == $lang['Realtor_Submit_Logo_Remove'])
     remove_image ( 'photos' , $f['id']);

    // If the Submit button was pressed we start this routine
    if (isset($_POST['submit_realtor']) 
    && $_POST['submit_realtor'] == $lang['Realtor_Submit'])
     {

      $form = array();

      // safehtml() all the POST variables
      // to insert into the database or
      // print the form again if errors
      // found
      $form = array_map('safehtml', $_POST);

      // Keep newlines.
      $form['realtor_description'] = safehtml_cms(@$_POST['realtor_description']);

      // Make password lower case
      $passwordin = $_POST['realtor_password'];

      // If password was not changed we do not update the
      // password field
      if ($_SESSION['password'] != $passwordin)
       $passwordin = md5($passwordin);
      else
       $passwordin = $session->fetch('password');

      // Cut the description if JS is disabled
      $form['realtor_description'] = substr ($form['realtor_description'], 0, $conf['realtor_description_size']);

      echo table_header ( $lang['Information'] );

      // Initially we think that no errors were found
      $count_error = 0;

      // Check for the empty or incorrect required fields

      if (empty($form['realtor_first_name']) || strlen($form['realtor_first_name']) < 2 )
       { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Realtor_First_Name'] . '</span><br />'; $count_error++;}

      if (empty($form['realtor_last_name']) || strlen($form['realtor_last_name']) < 2 )
       { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Realtor_Last_Name'] . '</span><br />'; $count_error++;}

      if (empty($form['realtor_city']) || strlen($form['realtor_city']) < 2 )
       { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['City'] . '</span><br />'; $count_error++;}

      if (empty($form['realtor_address']) || strlen($form['realtor_address']) < 4 )
       { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Realtor_Address'] . '</span><br />'; $count_error++;}

      if (empty($form['realtor_zip_code']) || strlen($form['realtor_zip_code']) < 4 )
       { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Zip_Code'] . '</span><br />'; $count_error++;}

      if (empty($form['realtor_phone']) || strlen($form['realtor_phone']) < 4 )
       { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Realtor_Phone'] . '</span><br />'; $count_error++;}

      if (empty($form['realtor_e_mail']) || strlen($form['realtor_e_mail']) < 4  || !valid_email($form['realtor_e_mail']))
       { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Realtor_e_mail'] . '</span><br />'; $count_error++;}

      if (empty($form['realtor_password']) || strlen($form['realtor_password']) < 4 )
       { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Realtor_Password'] . '</span><br />'; $count_error++;}

      if (!eregi('^[a-z0-9]+$', $form['realtor_password']))
       { echo $lang['Password_Incorrect'] . '<br />'; $count_error++;}

      // Check if both passwords are equal
      if ($form['realtor_password'] != $form['realtor_password_2'])
       { echo $lang['Passwords_Missmatch'] . '<br />'; $count_error++;}

      // Check if this email is already used
      if (strcasecmp($conf['allow_same_e_mail'], 'ON')) {
         $sql = 'SELECT id FROM ' . USERS_TABLE . ' WHERE email = "' . $form['realtor_e_mail'] . '" AND login <> "' . $session->fetch('login') . '"';
         $r = $db->query($sql) or error ('Critical Error', mysql_error () );
    
         if ($db->fetcharray($r) > 0 )
          { echo $lang['Email_Used'] . '<br />'; $count_error++;}
      }

      // If errors found we print out the number of errors
      if ($count_error > '0')
       echo '<br /><span class="warning">' . $lang['Errors_Found'] . ': ' . $count_error . '</span><br />';

      // If no errors were found during the above checks we continue
      if ($count_error == '0')
       {
        // Update user details in the database

        // Get the user IP address
        $user_ip = $_SERVER['REMOTE_ADDR'];
        // If there is more than one IP
        // get the first one from the 
        // comma separated list
        if ( strstr($user_ip, ', ') ) 
         {
          $ips = explode(', ', $user_ip);
          $user_ip = $ips[0];
         }

        // Create a mysql query
        $sql = 'UPDATE '. USERS_TABLE .
        ' SET first_name = "' . $form['realtor_first_name'] . '", 
	 last_name = "' . $form['realtor_last_name']. '",
	 company_name = "' . $form['realtor_company_name'] . '",
	 description = "' . $form['realtor_description'] . '",
	 location = "' . $form['realtor_location'] . '",
	 city = "' . $form['realtor_city'] . '",
	 zip = "' . $form['realtor_zip_code'] . '",
	 address = "' . $form['realtor_address'] . '",
	 phone = "' . $form['realtor_phone'] . '",
	 fax = "' . $form['realtor_fax'] . '",
	 mobile = "' . $form['realtor_mobile'] . '",
	 email = "' . $form['realtor_e_mail'] . '",
	 website = "' . $form['realtor_website'] . '",
	 date_updated = "' . date('Y-m-d') . '",
	 ip_updated = "' . $user_ip . '",
	 password = "' . $passwordin . '" WHERE login = "' . $session->fetch('login') . '"';

        $db->query($sql) or error ('Critical Error', mysql_error ());

        // Change current session password if user have changed his
        // password in the form

        $session->varunset('password');
        $session->set('password', $passwordin);

        // Output the 'Thank you' message
        // ..
        // If user needs approval we print a
        // different message
        if ($conf['approve_realtors'] == 'ON')
         echo $lang['Realtor_Listing_Updated_Approve'];
        else
         echo $lang['Realtor_Listing_Updated'];
       }

      echo table_footer ( );

     }

    // Navigation Menu

    echo table_header ( $lang['Menu_User_Login'] );

    echo ' <table cellpadding="5" cellspacing="0" border="0"> <tr>';
    // Add Listing Link

    // Fetching the listings number from the table
    $sql = 'SELECT id FROM ' . PROPERTIES_TABLE . ' WHERE userid = "' . $f['id'] . '"';
    $r_listings = $db->query( $sql );
    $res_listings = $db->numrows( $r_listings );

    // user currently has $res_listings posted

    // fetch the package and the number of listings allowed

    if ($f['package'] != '' && $f['package'] != '0')
    {
     // Fetch Packages
     $sql = 'SELECT * FROM ' . PACKAGES_AGENT_TABLE  . ' WHERE id = "' . $f['package'] . '" LIMIT 1';
     $r_package = $db->query ( $sql );
     $f_package = $db->fetcharray ( $r_package );
    }
   else
    {
     $f_package['listings'] = $conf['free_listings'];
    }

    // show the add listing link if user has less listings added than possible
    if ($res_listings <= $f_package['listings'])
     echo '<td width="80" align="center" valign="top"><a href="' . URL . '/adduserlistings.php"><img src="' . URL . '/templates/' . $cookie_template . '/images/icons/addlistings.png" border="0" alt=""><br />' . $lang['Add_Listings'] . '</a></td>';

    // View Listing Link with the number of listings displayed
    if ($res_listings > 0)
     echo '<td width="80" align="center" valign="top"><a href="' . URL . '/viewuserlistings.php"><img src="' . URL . '/templates/' . $cookie_template . '/images/icons/editlistings.png" border="0" alt=""><br />' . $lang['Edit_Listings'] . '</a> (' . $res_listings . ') </td>';

    echo ' </tr></table> ';

    echo table_footer();

    // Fetch all packages to show the paypal forms
    $sql = 'SELECT * FROM ' . PACKAGES_AGENT_TABLE;
    $r_packages = $db->query($sql) or error ('Critical Error', mysql_error () );

    if ($db->numrows($r_packages) > 0) {
        echo table_header ( $lang['Upgrade_Listing'] );
    }

    switch ($conf['paypal_mode']) {
    case 'TEST':
        $paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
        break;
    case 'LIVE':
        $paypal_url = 'https://www.paypal.com/cgi-bin/webscr';
        break;
    default:
        error('Configuration Error', 'paypal_mode can only be either LIVE or TEST. Check configuration screen.');
    }

    while ($f_packages = $db->fetcharray($r_packages))
     {

     // Do not show package we already have
     // if ($f_featured['package'] != $f_packages['id'])

    if ($conf['gateway'] == '2')
       echo '

       <form method="post" action="' . $conf['2co_gateway'] . '">
       <input type="submit" class="submit" value="' . $f_packages['name'] . ' (' . $f_packages['price'] . ')"> 
       <input type="hidden" name="sid" value="' . $conf['2co_user_id'] . '"> 
       <input type="hidden" name="product_id" value="' . $f_packages['position'] . '"> 
       <input type="hidden" name="quantity" value="1"> 
       <input type="hidden" name="merchant_order_id" value="USER-' . $session->fetch('login') . '-' . $f['id'] . '-' . $f_packages['id'] . '"> 
       </form>&nbsp;&nbsp;';

      if ($conf['gateway'] == '1')
       echo '

       <form action="'.$paypal_url.'" method="post">
       <input type="hidden" name="cmd" value="_xclick">
       <input type="hidden" name="business" value="' . $conf['paypal_email'] . '">
       <input type="hidden" name="return" value="' . URL . '/paypal-agents.php">
       <input type="hidden" name="notify_url" value="' . URL . '/paypal-agents.php">
       <input type="hidden" name="cancel_return" value="' . URL . '"> 
       <input type="hidden" name="invoice" value="' . date ( "YmdHis" ) . '">
       <input type="hidden" name="custom" value="' . $f['id'] . ':' . $f_packages['id'] . '">
       <input type="hidden" name="currency_code" value="' . $conf['paypal_currency'] . '">
       <input type="hidden" name="item_name" value="' . $f_packages['name'] . ' (' . $session->fetch('login') . ')">
       <input type="hidden" name="quantity" value="1">
       <input type="hidden" name="amount" value="' . $f_packages['price'] . '">
       <input type="hidden" name="no_shipping" value="1">
       <input type="hidden" name="rm" value="2">
       <input type="submit" class="submit" value="' . $f_packages['name'] . '">
       </form>&nbsp;&nbsp;';

     }
 
    if ($db->numrows($r_packages) > 0) {
        echo '<br />';
        echo table_footer ();
    }
    $db->freeresult($r_packages);

    // Upload logo/photo form

    echo table_header ( $lang['Realtor_Logo'] );

    // Output the form

    // Show user logo/picture if exist
    echo '<p align="center">' . show_image ('photos', $f['id']) . '</p>';

    echo '
     <form action="' . URL . '/login.php" method="POST" enctype="multipart/form-data">
      <table width="100%" cellpadding="5" cellspacing="0" border="0">
         ';

    echo userform ($lang['Realtor_Logo_File'], '<input type="file" size="40" name="logo_file" maxlength="50">', '1');
    echo userform ('', '<input type="Submit" name="submit_logo" value="' . $lang['Realtor_Submit_Logo'] . '"> <input type="Submit" name="submit_logo_remove" value="' . $lang['Realtor_Submit_Logo_Remove'] . '" onClick="return confirmDelete()" style="background: #E6BA9E; color: #000000;">');

    echo '
      </table>
     </form>
         ';

    // If image was uploaded
    if (isset($uploaded) && $uploaded)
     echo '<p align="center"><span class="warning">' . $lang['Realtor_Image_Uploaded'] . '</span></p>';

    // If image was not uploaded because of the image
    // size problems etc.
    if (isset($uploaded) && !$uploaded)
     echo '<p align="center"><span class="warning">' . $lang['Realtor_Image_NOT_Uploaded'] . '</span></p>';

    echo table_footer ();

    // Main form

    echo table_header ( $lang['Menu_Submit_Listing'] );

    // Fetch the results from the sql database and populate them into 
    // the form array
    $sql = 'SELECT * FROM ' . USERS_TABLE . ' WHERE login = "' . $session->fetch('login') . '" LIMIT 1';
    $r = $db->query ($sql) or error ('Critical Error', mysql_error () );
    $f = $db->fetcharray($r);

    // Define the form variables if the form was not updated
    if (!isset($form))
     {

      $form = array();
      $form['realtor_first_name'] = $f['first_name'];
      $form['realtor_last_name'] = $f['last_name'];
      $form['realtor_company_name'] = $f['company_name'];
      $form['realtor_description'] = $f['description'];
      $form['realtor_location'] = $f['location'];
      $form['realtor_city'] = $f['city'];
      $form['realtor_address'] = $f['address'];
      $form['realtor_zip_code'] = $f['zip'];
      $form['realtor_phone'] = $f['phone'];
      $form['realtor_fax'] = $f['fax'];
      $form['realtor_mobile'] = $f['mobile'];
      $form['realtor_e_mail'] = $f['email'];
      $form['realtor_website'] = $f['website'];
      $form['realtor_password'] = $f['password'];
  
     }

    else
     // Set new password if the form was changed
     $form['realtor_password'] = $passwordin;

    // Output the form
    echo '
     <form action="' . URL . '/login.php" method="POST">
      <table width="100%" cellpadding="5" cellspacing="0" border="0">
         ';

    echo userform ('ID', $f['id']);

    if ($f['package'] != '0' && $f['package'] != '')
     {

      $sql = 'SELECT * FROM ' . FEATURED_AGENTS_TABLE . ' WHERE id = ' . $f['id'];
      $r_featured = $db->query($sql) or error ('Critical Error', mysql_error () );
      $f_featured = $db->fetcharray($r_featured) or error ('Critical Error', mysql_error () );

      $sql = 'SELECT * FROM ' . PACKAGES_AGENT_TABLE . ' WHERE id = ' . $f['package'];
      $r_packages = $db->query($sql) or error ('Critical Error', mysql_error () );
      $f_packages = $db->fetcharray($r_packages) or error ('Critical Error', mysql_error () );

      echo userform ($lang['Admin_Packages_Name'], '<strong>' . $f_packages['name'] . '</strong>');
      echo userform ($lang['Admin_Listing_Expire'], printdate($f_featured['end_date']));
     }
    else
     {
      echo userform ($lang['Admin_Packages_Name'], '<strong>FREE</strong>');
      echo userform ($lang['Admin_Listing_Expire'], 'lifetime');
     }

    echo userform ($lang['Realtor_First_Name'], '<input type="text" size="45" name="realtor_first_name" value="' . $form['realtor_first_name'] . '" maxlength="255">', '1');
    echo userform ($lang['Realtor_Last_Name'], '<input type="text" size="45" name="realtor_last_name" value="' . $form['realtor_last_name'] . '" maxlength="255">', '1');
    echo userform ($lang['Realtor_Company_Name'], '<input type="text" size="45" name="realtor_company_name" value="' . $form['realtor_company_name'] . '" maxlength="255">');
    echo userform ($lang['Realtor_Description'], '<textarea wrap="soft" cols="45" rows="10"  name="realtor_description" onKeyDown="textCounter(this.form.realtor_description,this.form.realtor_description_counter, ' . $conf['realtor_description_size'] . ');" onKeyUp="textCounter(this.form.realtor_description,this.form.realtor_description_counter, ' . $conf['realtor_description_size'] . ');">' . html_entity_decode_utf8($form['realtor_description']) . '</textarea>');
    echo userform ('', '<input readonly type="text" name="realtor_description_counter" size="5" maxlength="5" value="' . $conf['realtor_description_size'] . '"> ' . $lang['Characters_Left']);
    echo userform ($lang['Location'], '<select name="realtor_location">' . generate_options_list(LOCATIONS_TABLE, $form['realtor_location']) . '</select>', '1');
    echo userform ($lang['City'], '<input type="text" size="45" name="realtor_city" value="' . $form['realtor_city'] . '" maxlength="50">', '1');
    echo userform ($lang['Realtor_Address'], '<input type="text" size="45" name="realtor_address" value="' . $form['realtor_address'] . '" maxlength="255">', '1');
    if (strcasecmp($conf['show_postal_code'], 'OFF')) 
        echo userform ($lang['Zip_Code'], '<input type="text" size="45" name="realtor_zip_code" value="' . $form['realtor_zip_code'] . '" maxlength="20">', '1');
    echo userform ($lang['Realtor_Phone'], '<input type="text" size="45" name="realtor_phone" value="' . $form['realtor_phone'] . '" maxlength="50">', '1');
    echo userform ($lang['Realtor_Fax'], '<input type="text" size="45" name="realtor_fax" value="' . $form['realtor_fax'] . '" maxlength="50">');
    echo userform ($lang['Realtor_Mobile'], '<input type="text" size="45" name="realtor_mobile" value="' . $form['realtor_mobile'] . '" maxlength="50">');
    echo userform ($lang['Realtor_e_mail'], '<input type="text" size="45" name="realtor_e_mail" value="' . $form['realtor_e_mail'] . '" maxlength="50">', '1');
    echo userform ($lang['Realtor_Website'], '<input type="text" size="45" name="realtor_website" value="' . $form['realtor_website'] . '" maxlength="255">');
    echo userform ($lang['Realtor_Password'], '<input type="password" size="45" name="realtor_password" value="' . $form['realtor_password'] . '" maxlength="50">', '1');
    echo userform ($lang['Realtor_Password_Repeat'], '<input type="password" size="45" name="realtor_password_2" value="' . $form['realtor_password'] . '" maxlength="50">', '1');
    // Submit button
    echo userform ('', '<input type="Submit" class="submit" name="submit_realtor" value="' . $lang['Realtor_Submit'] . '">');

    echo '
      </table>
     </form>
         ';
  
    echo table_footer ();

    // Statistics

    echo table_header ( $lang['Information'] );
    // Submission date
    echo '<span class="bold">' . $lang['Listing_Added_Date'] . ':</span> ' . printdate($f['date_added']) . ' (' . $f['ip_added'] . ', ' . gethostbyaddr($f['ip_added']) . ') <br />';
    // Update date
    if (!empty($f['date_updated']))
     echo '<span class="bold">' . $lang['Listing_Updated_Date'] . ':</span> ' . printdate($f['date_updated']) . ' (' . $f['ip_updated'] . ', ' . gethostbyaddr($f['ip_updated']) . ') <br />';
    // Number of visitors
    echo '<span class="bold">' . $lang['Hits'] . ':</span> ' . $f['hits'] . ' <br />';
  
    echo table_footer ();

   }

  else 

   echo $lang['Not_Approved'];

 }

else

 {

  // IF NOT LOGGED we print out the login form

  // If this form was already submitted and 
  // login / password are not correct
  // we destroy the session

  if (isset($_SESSION['login'])
  && !auth_check($session->fetch('login'), $session->fetch('password')) 
  && isset($_POST['login'])) 

   $session->destroy();

  echo table_header ( $lang['Menu_User_Login'] );

  // Output the form
  echo '
   <form action="' . URL . '/login.php" method="POST">
    <table width="100%" cellpadding="5" cellspacing="0" border="0">
       ';

  echo userform ($lang['Realtor_Login'], '<input type="text" size="45" name="login" maxlength="50">');
  echo userform ($lang['Realtor_Password'], '<input type="password" size="45" name="password" maxlength="50">');
  echo userform ('', '<input type="submit" class="submit" value="' . $lang['Realtor_Login'] . '">');

  echo '
    </table>
   </form>
       ';

  echo table_footer ();
  // If 
  if (isset($userlogin) && !$userlogin = FALSE) 
   // Print login error if login/password is incorrect
   echo '<span class="warning">' . $lang['Auth_Error'] . '</span><br /><br />';

  // Password reminder link
  echo '[ <a href="' . URL . '/reminder.php">' . $lang['Password_Reminder'] . '</a> ]<br /><br />';

 }

// Template footer
include ( PATH . '/templates/' . $cookie_template . '/footer.php' );

?>